package jlu.com.p2pclient.activity;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jlu.mcloud.communicate.fileio.FileEntity;
import com.jlu.mcloud.communicate.fileio.FileIoHandler;
import com.jlu.mcloud.communicate.fileio.FileWriter;
import com.jlu.mcloud.rpc.client.RPCClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

import jlu.com.p2pclient.R;
import jlu.com.p2pclient.service.HeartBeatService;
import jlu.com.p2pclient.utils.Config;
import jlu.com.p2pclient.utils.HeartBeatListerner;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private TextView tvMsg;
    private EditText txtIP, txtPort, txtEt;
    private Button btnSend;
    private Button btnLoad;
    private android.os.Handler handler;
    private File file;
    private HeartBeatService myBinder;

    /*绑定服务*/
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = ((HeartBeatService.HeartbeatBinder) service).getService();
            myBinder.setHeartBeatListener(new HeartBeatListerner() {
                @Override
                public void isConnected(String result) {
                    boolean flag = Config.SERVER_REPLY.equals(result) ? true : false;
                    if (flag) {
                        Message.obtain(handler, 1, "本机IP：" + Config.getHostIp() + " 监听端口:" + Config.SERVER_PORT + "\t在线中").sendToTarget();
                    } else {
                        Message.obtain(handler, 1, "本机IP：" + Config.getHostIp() + " 监听端口:" + Config.SERVER_PORT + "\t离线中").sendToTarget();
                    }

                }
            });

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //找到控件
        initView();
        txtIP.setText(Config.SERVER_IP);
        txtPort.setText(Config.SERVER_PORT + "");
        tvMsg.setText("本机IP：" + Config.getHostIp() + " 监听端口:" + Config.SERVER_PORT + "\t离线中");
        //选择文件发送
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseFile();
            }
        });

        /*选择文件下载*/
        btnLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent loadIntent = new Intent(getApplicationContext(), FileNameActivity.class);
                startActivityForResult(loadIntent, 1);
            }
        });

        /*使用handler更新edittext内容*/
        handler = new android.os.Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                        txtEt.append("\n[" + format.format(new Date()) + "]" + msg.obj.toString());
                        break;
                    case 1:
                        tvMsg.setText("");
                        tvMsg.setText(msg.obj.toString());
                        break;
                    default:
                        break;
                }
            }
        };

    }
    /**
     * see   跳转页面反馈结果处理
     *
     * @入参
     * @出参
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    // Get the Uri of the selected file
                    Uri uri = data.getData();
                    String path = Config.getFilePathFromUri(MainActivity.this, uri);
                    if (null != path) {
                        file = new File(path);
                        final String fileName = file.getName();
                        /*发送消息给handler*/
                        Message.obtain(handler, 0, fileName + " 正在发送至" + Config.SERVER_IP + ":" + Config.SERVER_PORT).sendToTarget();
                        /*发送手机文件到服务器*/
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                FileWriter writer = new FileWriter(Config.SERVER_IP, Config.SERVER_PORT) {
                                    /*写入手机序列号*/
                                    @Override
                                    protected String getNodeId() {
                                        return Config.DEVICE_ID;
                                    }
                                };
                                try {
                                    writer.write(file);
                                    Message.obtain(handler, 0, fileName + "发送成功").sendToTarget();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                            }
                        }).start();
                    } else {
                        Log.v(TAG, "文件路径不能为空");
                    }
                }
                break;
            case 1:
                if (resultCode == RESULT_OK) {
                    final String fileName = data.getStringExtra("fileName");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            FileIoHandler fileHandler = RPCClient.getRemoteProxyObject(FileIoHandler.class, new InetSocketAddress(
                                    Config.SERVER_IP, Config.SERVER_PORT
                            ));
                            try {
                                FileEntity fileEntity = fileHandler.readFile(fileName);
                                //TODO 存到手机目录
                                if (fileEntity.getLength() > 0) {
                                    //获取当前目录
                                    File dir = getFilesDir();
                                    //文件存入路径
                                    String savePath = dir.getPath() + Config.FILESEPARATOR + fileName;
                                    Log.w(TAG, savePath);
                                    FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath));
                                    if (fileOutputStream != null) {
                                        fileOutputStream.write(fileEntity.getData());
                                        fileOutputStream.flush();
                                        fileOutputStream.close();
                                        Message.obtain(handler, 0, fileName + "接收成功").sendToTarget();
                                    } else {
                                        Message.obtain(handler, 0, fileName + "接收失败").sendToTarget();
                                    }
                                } else {
                                    Message.obtain(handler, 0, fileName + "接收失败").sendToTarget();
                                }

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * see   获取手机文件目录
     *
     * @入参 void
     * @出参 void
     */
    private void chooseFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 0);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(MainActivity.this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * see   找到控件
     *
     * @入参
     * @出参
     */
    private void initView() {
        tvMsg = (TextView) findViewById(R.id.tvMsg);
        txtIP = (EditText) findViewById(R.id.txtIP);
        txtPort = (EditText) findViewById(R.id.txtPort);
        txtEt = (EditText) findViewById(R.id.et);
        btnLoad = (Button) findViewById(R.id.btnLoad);
        btnSend = (Button) findViewById(R.id.btnSend);
    }

    //创建菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    //设置菜单点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent(MainActivity.this, HeartBeatService.class);
        switch (item.getItemId()) {

            /*绑定服务*/
            case R.id.bind_service:
                Toast.makeText(MainActivity.this, "开启服务", Toast.LENGTH_SHORT).show();
                bindService(intent, serviceConnection, BIND_AUTO_CREATE);

                break;

            /*解除绑定*/
            case R.id.unbind_service:
                tvMsg.setText("本机IP：" + Config.getHostIp() + " 监听端口:" + Config.SERVER_PORT + "\t离线中");
                stopService(intent);
                unbindService(serviceConnection);
                break;

            case R.id.about:
                AlertDialog aDialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("freedom出品，必属精品~")
                        .setMessage("邮箱：18844545194@163.com\n联系我吧~~")
                        .setIcon(R.mipmap.ic_launcher)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
                                        dialog.cancel();
                                    }
                                }).show();
                break;
            case R.id.connect_nodes:
                //TODO 获取连接节点
                break;


            default:
                break;
        }
        return true;
    }

    //退出询问
    @Override
    public void onBackPressed() {
        // 该方法仅适用于2.0或更新版的sdk
        android.app.AlertDialog aDialog = new android.app.AlertDialog.Builder(MainActivity.this)
                .setTitle(" 温馨提示 ")
                .setMessage("您确定退出吗？")
                .setIcon(R.mipmap.ic_launcher)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        System.exit(0);
                        MainActivity.this.finish();
                    }
                }).show();
        return;
    }


}
